﻿using System;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using Cms.Domain;
using Cms.Domain.Authentication;
using Cms.Web.Framework.Extensions;
using Cms.Web.Framework.Infrastructure;
using iLib.Web.UI;

namespace Cms.Web.Framework.Controls
{
    public class SitePreview : Page
    {
        protected SitePreview()
        {
            RequestDetails = (RequestDetails)HttpContext.Current.Items["RequestDetails"];
            if (HttpContext.Current.Request.QueryString["TestDetailTemplate"] != null &&
                HttpContext.Current.Request.QueryString["TestDetailTemplate"] == "true")
            {
                AuthenticatedUser user = Conversion.ToAuthenticatedUser(Context.User.Identity.Name);
                MasterPageFile = "~/Admin/Resources/Temp/" + user.AdministratorID + "/TestDetailTemplate.master";
                return;
            }
            if (RequestDetails.DetailTemplate != null)
                MasterPageFile = "~/__System/DetailTemplates/" + RequestDetails.DetailTemplate.ID + ".master";
            else
                MasterPageFile = "~/Admin/Resources/DummyDetailTemplate.master";
        }
        
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Header.Controls.AddAt(0, new LiteralControl("<base href=\"" + Url.FullPath + "\" />"));
            CollectTemplateAreaIDsAndStoreThemInResponseHeader();
        }
        
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Page.Header.Controls.Add(new iLibRegistrator());
        }
        
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (RequestDetails.MasterTemplate == null)
                return;
            foreach (
                Stylesheet stylesheet in
                    RequestDetails.MasterTemplate.GetStylesheets().Where(
                        stylesheet => stylesheet.Context == StylesheetContext.Always))
            {
                Header.Controls.Add(new LiteralControl("<link rel=\"stylesheet\" type=\"text/css\" href=\"" +
                                                       Url.VirtualPath + "__System/Stylesheets/" +
                                                       stylesheet.ID + ".css?v=" +
                                                       stylesheet.SourceCode.CurrentVersion.Timestamp + "\" />"));
            }
            Page.Header.Controls.Add(
                new LiteralControl(
                    "<link type=\"text/css\" rel=\"stylesheet\" href=\"Admin/Css/SitePreview.css?v=1\" />"));
            Page.AddHeaderScriptInclude(ConfigurationManager.AppSettings["jQueryPath"]);
            Page.AddHeaderScript("sitePreviewMultipleJQueryIncludesFix", "var cms$ = $; $.noConflict(true);");
            Page.AddHeaderScriptInclude("Admin/Js/CmsLib.js");
            Page.AddHeaderScriptInclude("Admin/Js/SitePreview.js?v=5");
            Page.AddHeaderScript("sitePreviewInit", "cms.SitePreview.Init();");
        }
        
        protected override void OnPreRenderComplete(EventArgs e)
        {
            // Hide base method
        }

        private void CollectTemplateAreaIDsAndStoreThemInResponseHeader()
        {
            string masterTemplateAreas = string.Empty;
            string masterTemplatePageAreas = string.Empty;
            string detailTemplateAreas = string.Empty;
            string detailTemplatePageAreas = string.Empty;
            foreach (Content c in RequestDetails.ContentPlaceHolders)
            {
                if (c is MasterTemplateContent)
                {
                    if (masterTemplateAreas != string.Empty)
                        masterTemplateAreas += ",";
                    masterTemplateAreas += c.ID;
                }
                else if (c is DetailTemplateContent)
                {
                    if (detailTemplateAreas != string.Empty)
                        detailTemplateAreas += ",";
                    detailTemplateAreas += c.ID;
                }
                else if (c is PageContent)
                {
                    if (c.Parent is DetailTemplatePlaceHolder)
                    {
                        if (detailTemplatePageAreas != string.Empty)
                            detailTemplatePageAreas += ",";
                        detailTemplatePageAreas += c.ID;
                    }
                    else
                    {
                        if (masterTemplatePageAreas != string.Empty)
                            masterTemplatePageAreas += ",";
                        masterTemplatePageAreas += c.ID;
                    }
                }
            }

            // This info is used when saving the source code for master- and detail templates.
            // The information is stored as headers instead of in RequestDetails so it can be retrieved 
            // when using HttpWebResponse.GetResponse();
            Response.AddHeader("MasterTemplateAreas", masterTemplateAreas);
            Response.AddHeader("MasterTemplatePageAreas", masterTemplatePageAreas);
            Response.AddHeader("DetailTemplateAreas", detailTemplateAreas);
            Response.AddHeader("DetailTemplatePageAreas", detailTemplatePageAreas);
        }
    }
}